package cn.edu.tju.elm.repository;

import cn.edu.tju.elm.common.constants.RuleType;
import cn.edu.tju.elm.model.entity.RewardRule;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

@Repository
public interface RewardRuleRepository extends JpaRepository<RewardRule, Long> {

    List<RewardRule> findByRuleTypeAndIsActiveTrue(RuleType ruleType);

    // 修复这个方法，确保只返回一个结果
    @Query("SELECT r FROM RewardRule r WHERE r.ruleType = :ruleType AND r.isActive = true " +
            "AND (:amount IS NULL OR r.conditionAmount <= :amount) " +
            "ORDER BY r.conditionAmount DESC LIMIT 1")
    Optional<RewardRule> findTopRechargeRuleByAmount(
            @Param("ruleType") RuleType ruleType,
            @Param("amount") BigDecimal amount);

    List<RewardRule> findByIsActiveTrue();

    // 新增：根据 ruleKey 查找
    Optional<RewardRule> findByRuleKey(String ruleKey);

    // 新增：检查 ruleKey 是否存在
    boolean existsByRuleKey(String ruleKey);
}